package l1j.server.server.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.L1DatabaseFactory;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.utils.Random;
import l1j.server.server.utils.SQLUtil;
import l1j.server.server.utils.collections.Maps;

public class MapDropTable {
	private static Logger _log = Logger.getLogger(MapDropTable.class.getName());

	private static MapDropTable _instance = new MapDropTable();

	private static Map<Integer, Set<MapDrop>> _drops = Maps.newMap();

	public static MapDropTable getInstance() {
		return _instance;
	}

	public static void initilize() {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {

			con = L1DatabaseFactory.getInstance().getConnection();
			pstm = con.prepareStatement("SELECT * FROM x_droplist_map");
			rs = pstm.executeQuery();
			while (rs.next()) {
				int mapId = rs.getInt("mapId");
				if (!_drops.containsKey(mapId)) {
					_drops.put(mapId, new HashSet<MapDrop>());
				}
				MapDrop m = _instance.new MapDrop();
				m.chance = rs.getInt("chance");
				m.item_id = rs.getInt("itemId");
				m.min = rs.getInt("min");
				m.max = rs.getInt("max");
				_drops.get(mapId).add(m);
			}
		} catch (SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public void setDrop(L1NpcInstance mon) {
		if (_drops.containsKey((int) mon.getMapId())) {
			for (MapDrop m : _drops.get((int) mon.getMapId())) {
				if (Random.chance(m.chance, 1000000)) {
					int count = Random.nextInt(m.max - m.min, m.min);
					L1ItemInstance item = ItemTable.getInstance().createItem(
							m.item_id);
					item.setCount(count);
					mon.getInventory().storeItem(item);
				}
			}
		}

	}

	class MapDrop {
		public int chance;
		public int item_id;
		public int max;
		public int min;
	}
}
